<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 后台首页
 *
 * @author      Eden
 * @datetime    2016/11/24 21:57
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Home extends ADM_Controller
{

    /**
     * 主页
     */
    public function index()
    {
        if ($this->role == 'base' && $this->baseId > 0) {



            $db = clone ($this->db);
            $q = $db->get_where('base_bill_apply', ['baseId' => $this->baseId]);
            $item = $q->row_array();
            $this->load->view(parent::TMP_DIR . '/home/base.html', [
                'bill' => $item,
                'order' => $this->order($this->baseId),
                'amount' => $this->getThisMonthAmount($this->baseId),
                'summary' => $this->summary($this->baseId)
            ]);
        } else {
            $this->load->view(parent::TMP_DIR . '/home/home.html');
        }
    }

    /**
     * @param $baseId
     * @return array
     */
    private function summary($baseId)
    {
        $returns = [
            'goods' => 0,
            'user' => 0
        ];

        $db = clone($this->db);
        $db->where(['baseId' => $baseId]);
        $returns['user'] = $db->count_all_results('admin');

        $db1 = clone($this->db);
        $db1->where('baseId', $baseId);
        $returns['goods'] = $db1->count_all_results('base_goods');

        return $returns;

    }

    /**
     * @param $baseId
     * @return int|string
     */
    private function getThisMonthAmount($baseId)
    {
        $db = clone ($this->db);
        $q = $db->get_where('user_order', [
            'created <= ' => date('Y-m-d 23:59:59'),
            'created >= ' => date('Y-m-01 00:00:00'),
            'baseId' => $baseId
        ]);
        $rows = $q->result_array();
        if (empty($rows)) {
            return 0;
        }

        $total = 0;
        foreach ($rows as $row) {
            $total += intval($row['totalPrice']);
        }

        return money_format('%i', $total / 100);
    }

    /**
     * @param $baseId
     */
    private function order($baseId)
    {
        $return = [
            'today' => 0,
            'total' => 0
        ];
        $db = clone($this->db);
        $db->where([
            'baseId' => $baseId,
            'created >=' => date('Y-m-d 00:00:00'),
            'created <=' => date('Y-m-d 23:59:59')
        ]);
        $return['today'] = $db->count_all_results('user_order');

        $db2 = clone ($this->db);
        $db2->where([
            'baseId' => $baseId
        ]);
        $return['total'] = $db2->count_all_results('user_order');
        return $return;
    }

    /**
     * 顶部概览
     */
    public function getSummary()
    {
        $this->load->model('admin/stat/Summary_Model', 's');
        $total = $this->s->getTotal();
        $summary = $this->s->getSummary();
        $this->output->send([
            'state' => true,
            'data' => [
                'total' => $total,
                'today' => $summary,
            ]
        ]);
    }

    /**
     * 首页图表
     */
    public function getSummaryChart()
    {
        $this->load->model('admin/stat/Summary_Model', 'stat');
        $stats = $this->stat->getSummaryChart(14);
        $this->output->send(['state' => true, 'data' => $stats]);
    }

    /**
     * 最新记录
     */
    public function getLatest()
    {
        // 最新用户
        $this->load->model('admin/user/User_Model', 'user');
        $users = $this->user->getLatestUsers(8);
        if (!empty($users) && is_array($users)) foreach($users as &$item) {
            $item['created'] = formateTimeStamp($item['created']);
        } else {
            $users = [];
        }
        unset($item);

        // 最新农场
        $this->load->model('admin/base/Common_Model', 'base');
        $bases = $this->base->getLatestBases(3);
        if (!empty($bases)&& is_array($bases)) foreach($bases as &$item) {
            $item['thumb'] = thumb($item['thumb'], 100, 100);
        }
        unset($item);

        // 最新产品
        $this->load->model('admin/goods/Goods_Model', 'goods');
        $products = $this->goods->getLatestProducts(8);
        if (!empty($products) && is_array($products)) foreach($products as &$item) {
            $item['price'] = money_format('%i', $item['minPrice'] / 100);
            $item['thumb'] = thumb($item['thumb'], 100, 100);
        }

        // 最新订单
        $this->load->model('admin/order/Order_Model', 'order');
        $orders = $this->order->getLatestOrders(8);

        $this->output->send([
            'state' => true,
            'data' => [
                'users' => $users,
                'bases' => $bases,
                'products' => $products,
                'orders' => $orders
            ]
        ]);
    }

    /**
     * 测试案列
     */
    public function url()
    {
        // $url = 'http://m.api.imaumm.com';
        // $url = 'http://api.shop.dev';
        $url = 'http://m.api.qiuqiugu.com';
        $secret = '202cb962ac59075b964b07152d234b70';
        $time = time();

        $params = array(
            'version' => '1.0.0',
            'deviceId' => 'CCBAEB6E-559B-46A9-926B-BFCDE89F01F6',
            'time' => $time,
            'type' => 'ios',
            'ip' => '192.168.1.10',
            'module' => 'refundview',
            'orderId' => 92,
            'userId' => 32,
            'sn' => 'BA11357150336950',
            'payType' => 'wechat'
        );


        ksort($params);
        $query = http_build_query($params, '_', '&', PHP_QUERY_RFC3986);
        $sign = md5(md5($query) . $secret . $time);

        $params = array_merge($params, array('token' => $sign));

        echo $url . '/v1/order?' . http_build_query($params, '_', '&', PHP_QUERY_RFC3986);
        //echo 'http://cms.pkg.dev/regist?' . http_build_query($params, '_', '&', PHP_QUERY_RFC3986);

    }

    public function express()
    {
        $this->load->library('util/Util_AliExpress', null, 'ali');
        $res = $this->ali->ask('shentong', '3317401860776');
        var_dump($res);
    }

    public function sms()
    {
        $this->config->load('sms');
        $sms_config = $this->config->item('sms');
        $this->load->library('util/Util_Sms', array(
            'template' => $sms_config['tpl']['regist']
        ), 'UtilSms');

        $res = $this->UtilSms->send('18001032230',array('{code}' => rand(1000, 9999)));
        var_dump($res);
    }

    public function qiniu()
    {
        $this->load->library('util/Util_Qiniu', null, 'qiniu');
        echo  $this->qiniu->test();
    }

    public function wechat()
    {
        $this->load->model('common/Cash_Model', 'cash');
        $this->cash->doTransfer();
    }
}
